package com.qiche.util;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.qiche.config.YmlConfig;
import com.qiche.dto.PiccCard;
import com.qiche.model.Merchant;
import com.qiche.service.impl.EnchashmentServiceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ApiUtils {

	private static final Logger log = LoggerFactory.getLogger(ApiUtils.class);

	@Autowired
	private static YmlConfig ymlConfig;

	/**
	 * 该接口用于外部系统向卡券系统 发送卡券
	 * 
	 * @param cards
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public boolean postCard(List<PiccCard> cards) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new Gson();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("json", cards);
		map.put("token", token);
		String sendUrl = ymlConfig.getKqSysUrl();
		String responseBody = HttpUtils.sendPost(sendUrl + "/postCard", gson.toJson(map));
		System.out.println(responseBody);
		Map<String, String> result = gson.fromJson(responseBody, HashMap.class);
		if ("200".equals(result.get("code").toString())) {
			return true;
		}
		return false;
	}

	/**
	 * 该接口用于外部系统远程 更新 卡券系统的卡券核销状态
	 * 
	 * @param cardCode
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public boolean toWriteOff(String cardCode) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new Gson();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("cardCode", cardCode);
		map.put("token", token);
		String sendUrl = ymlConfig.getKqSysUrl();
		String responseBody = HttpUtils.sendPost(sendUrl + "/toWriteOffed", gson.toJson(map));
		System.out.println(responseBody);
		Map<String, String> result = gson.fromJson(responseBody, HashMap.class);
		if ("200".equals(result.get("code").toString())) {
			return true;
		}
		return false;
	}

	/**
	 * 该接口用于外部系统远程 核销人保卡券系统的卡券
	 * 
	 * @param cardCode
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> writeOffPicc(String cardCode, String piccUid, String piccMid) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		/*
		 * Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new
		 * JsonSerializer<Double>() {
		 * 
		 * @Override public JsonElement serialize(Double src, Type typeOfSrc,
		 * JsonSerializationContext context) { if (src == src.longValue())
		 * return new JsonPrimitive(src.longValue()); return new
		 * JsonPrimitive(src); } }).create();
		 */
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("cardCode", cardCode);
		map.put("piccUid", piccUid);
		map.put("piccMid", piccMid);
		map.put("token", token);
		String sendUrl = ymlConfig.getKqSysUrl();
		String responseBody = HttpUtils.sendPost(sendUrl + "/writeOffPicc", JSON.toJSONString(map));
		System.out.println(responseBody);

		Map<String, Object> result = (Map<String, Object>) JSON.parse(responseBody);
		// Map<String, String> result = gson.fromJson(responseBody,
		// HashMap.class);
		return result;
	}

	/**
	 * 该接口查询登录用户是否是人保的账号
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> queryPiccUser(String username, String password) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
			@Override
			public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
				if (src == src.longValue())
					return new JsonPrimitive(src.longValue());
				return new JsonPrimitive(src);
			}

		}).create();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("username", username);
		map.put("password", password);
		map.put("token", token);
		String sendUrl = ymlConfig.getKqSysUrl();
		String responseBody = HttpUtils.sendPost(sendUrl + "/QueryPiccUser", gson.toJson(map));
		System.out.println(responseBody);

		Map<String, String> result = JSON.parseObject(responseBody, new TypeReference<HashMap<String, String>>() {
		});
		System.out.println(result);

		return result;

	}

	/**
	 * 该接口查询卡券系统的门店
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public JSONArray getPiccStores() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new Gson();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("token", token);
		String sendUrl = ymlConfig.getKqSysUrl();
		String responseBody = HttpUtils.sendPost(sendUrl + "/getStores", gson.toJson(map));
		System.out.println(responseBody);

		Map<String, String> result = JSON.parseObject(responseBody, new TypeReference<HashMap<String, String>>() {
		});

		JSONArray array = JSON.parseArray(result.get("stores"));

		return array;

	}

	public static Map<String, Object> transferBatch(Map<String, Object> map) throws Exception {
		Gson gson = new Gson();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("token", token);
		String responseBody = HttpUtils.sendPost(ymlConfig.getTransferBatchUrl(), gson.toJson(map));
		log.info("批量转账响应数据：{}", responseBody);

		Map<String, Object> result = JSON.parseObject(responseBody, new TypeReference<HashMap<String, Object>>() {
		});

		return result;

	}

	public static Map<String, Object> transfer(Map<String, Object> map) throws Exception {
		Gson gson = new Gson();
		DesUtils des = new DesUtils("YHL_ojbk");
		String token = des.encrypt("dxfq");
		map.put("token", token);
		String responseBody = HttpUtils.sendPost(ymlConfig.getTransferUrl(), gson.toJson(map));
		log.info("单笔转账响应数据：{}", responseBody);

		Map<String, Object> result = JSON.parseObject(responseBody, new TypeReference<HashMap<String, Object>>() {
		});

		return result;

	}

	/**
	 * 微信获取accessToken
	 * 
	 * @param merchant
	 * @param code
	 * @return
	 */
	public static JSONObject wxAccessToken(String appid,String appSecret, String code) {
		String params = "appid=" + appid + "&secret=" + appSecret + "&code=" + code
				+ "&grant_type=authorization_code";
		// 发送请求 获取access_token
		String sr = HttpUtils.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
		// 解析相应内容（转换成json对象）
		JSONObject json = JSONObject.parseObject(sr);
		return json;
	}
	
	/**
	 * 微信获取accessToken
	 * 
	 * @param merchant
	 * @return
	 */
	public static JSONObject wxAccessToken(Merchant merchant) {
		String params = "grant_type=client_credential&appid=" + merchant.getAppid() + "&secret="
				+ merchant.getAppSecret();
		// 发送请求 获取access_token
		String sr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
		// 解析相应内容（转换成json对象）
		JSONObject json = JSONObject.parseObject(sr);
		return json;
	}
	
	/**
	 * 微信获取用户信息
	 * @param accesstoken
	 * @param openid
	 * @return
	 */
	public static JSONObject wxUserinfo(String accesstoken, String openid) {
		// 请求参数
		String userinfoParams = "access_token=" + accesstoken + "&openid=" + openid + "&lang=zh_CN";
		// 发送请求 获取用户信息
		String userinfo = HttpUtils.sendGet("https://api.weixin.qq.com/sns/userinfo", userinfoParams);
		// 解析相应内容（转换成json对象）
		JSONObject userinfoJson = JSONObject.parseObject(userinfo);
		return userinfoJson;

	}

	/**
	 * 微信获取 jsapi_ticket
	 * 
	 * @param accesstoken
	 * @return
	 */
	public static JSONObject wxJsapiTicket(String accesstoken) {
		String jsapiTicketParams = "access_token=" + accesstoken + "&type=jsapi";
		String jsapiTicket = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", jsapiTicketParams);
		// 注意这里参数名必须全部小写，且必须有序
		// 解析相应内容（转换成json对象）
		JSONObject jsapiTicketJson = JSONObject.parseObject(jsapiTicket);
		return jsapiTicketJson;

	}

	public static void main(String[] args) throws Exception {

	}

}
